package casa.depesos.app.com.frag;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import casa.depesos.app.com.R;
import casa.depesos.app.com.adapter.OrderListAdapter;
import casa.depesos.app.com.databinding.FragmentOrderBinding;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.OrderBean;
import casa.depesos.app.com.http.req.OrdersReq;


public class OrderFragment extends BaseFragment {

    String status;
    FragmentOrderBinding binding;
    OrderListAdapter adapter;

    public OrderFragment setStatus(String status) {
        this.status = status;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentOrderBinding.inflate(inflater, container, false);
        binding.list.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new OrderListAdapter();
        binding.list.setAdapter(adapter);

        if (getUserVisibleHint()) {
            getData();
        }

        return binding.getRoot();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && adapter != null && adapter.getItemCount() == 0) {
            getData();
        }
    }

    public void getData() {
        showLoading();
        binding.empty.setVisibility(View.INVISIBLE);
        clearFragment();
        new OrdersReq(status).req(new ReqCallback<OrderBean>() {
            @Override
            public void callback(boolean success, OrderBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    adapter.setList(bean.list);
                } else if (bean == null) {
                    replaceFragment(R.id.frame, new NetFailFragment().setTitle("", false));
                }
                if (adapter.getItemCount() == 0) {
                    binding.list.setVisibility(View.INVISIBLE);
                    binding.empty.setVisibility(View.VISIBLE);
                } else {
                    binding.list.setVisibility(View.VISIBLE);
                }
            }
        });

        getChildFragmentManager().getFragments();
    }
}
